﻿using Module.Common.PubEvent;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace PrismChessApp.ViewModels
{
    /// <summary>
    /// 消息记录
    /// </summary>
    public class MessageLogViewModel : BindableBase
    {
        private string _messageLogText;
        public string MessageLogText { get { return _messageLogText; } set { SetProperty(ref _messageLogText, value); } }
        private int index;
        public DataTable MessageData { get; set; }
        public MessageLogViewModel(IEventAggregator ea)
        {
            MessageData = new();
            MessageData.Columns.Add("id", typeof(int));
            MessageData.Columns.Add("time", typeof(string));
            MessageData.Columns.Add("eventName", typeof(string));
            MessageData.Columns.Add("ModuleName",typeof(string));
            MessageData.Columns.Add("sender", typeof(string));
            MessageData.Columns.Add("messageName", typeof(string));
            MessageData.Columns.Add("content", typeof(string));

            ea.GetEvent<ModuleMessageEvent>().Subscribe(ReciewMessage,ThreadOption.UIThread);
            ea.GetEvent<SystemMessageEvent>().Subscribe(ReciewSystemMessage, ThreadOption.UIThread);
            ea.GetEvent<ServiceMessageEvent>().Subscribe(ServiceMessageProcess, ThreadOption.UIThread);
            ea.GetEvent<QiPuMessageEvent>().Subscribe(ReciewQiPuMessage, ThreadOption.UIThread);
            ea.GetEvent<ReplyMessageEvent>().Subscribe(ReciewReplyMessage, ThreadOption.UIThread);
        }
        private void ReciewReplyMessage(ReplyMessage obj)
        {
            AddMessageRecord(obj);
        }
        private void ServiceMessageProcess(ServiceMessage obj)
        {
            AddMessageRecord(obj);
        }

        private void ReciewQiPuMessage(QiPuMessage obj)
        {
            AddMessageRecord(obj);
        }

        private void ReciewSystemMessage(SystemMessage obj)
        {
            AddMessageRecord(obj);
        }

        private void ReciewMessage(ModuleMessage obj)
        {
            AddMessageRecord(obj);
        }
        private void AddMessageRecord(MessageBass message)
        {
            if (MessageData.Rows.Count > 50) MessageData.Rows.RemoveAt(0); // 超过100条信息则清空
            index++;
            DataRow dr = MessageData.NewRow();
            dr["id"] = index;
            dr["time"] = message.TimeStamp;
            dr["eventName"] = message.MessageEventName;
            dr["ModuleName"] = message.ModuleName;
            dr["sender"] = message.SenderFrom;
            dr["messageName"] = message.MessageName;
            dr["content"] = message.Content;
            MessageData.Rows.Add(dr);
            MessageData.DefaultView.Sort = "time ASC"; // 按时间先后排序
        }
    }
}
